#include <iostream>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include "Mutex.hpp"

//用户个数
#define UserNum 20

//总票数
long TicketNum = 10;

//创建全局锁变量
pthread_mutex_t ticket_lock;

//线程调用的函数
void *GetTicket(void *args)
{
    //获取线程的编号
    long int user_id = reinterpret_cast<long>(args);

    {
        MutexGuard mutexguard(&ticket_lock);
        if (TicketNum > 0)
        { //剩余票
            //获取余票
            TicketNum--;

            printf("User : %ld 抢到票！余票：%ld\n", user_id, TicketNum);

            //---- 解锁 ----//
            pthread_mutex_unlock(&ticket_lock);

            //模拟抢到票后操作
            usleep(1000);
        }
        else
        {
            printf("User : %ld 没有余票了！\n", user_id);

            //---- 解锁 ----//
            pthread_mutex_unlock(&ticket_lock);

            //模拟抢到未票后操作
            usleep(1000);
        }
    }

    return nullptr;
}

int main()
{

    //初始化锁变量
    pthread_mutex_init(&ticket_lock, nullptr);

    printf("------------- 抢票开始 -------------\n");

    std::vector<pthread_t> Threads(20); //二十个人一起抢票

    //创建线程
    for (long i = 1; i <= UserNum; i++)
    {
        pthread_create(&Threads[i - 1], nullptr, GetTicket, reinterpret_cast<void *>(i));
    }

    //等待所有的线程
    for (long i = 1; i <= UserNum; i++)
    {
        pthread_join(Threads[i - 1], nullptr);
    }

    printf("------- 抢票结束！余票为: %ld -------\n", TicketNum);
    return 0;
}
